package com.solution.util;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.solution.model.Communication;
import com.solution.util.GJMailAuthenticator;

public class EmailSender{
	private static String contentAndEncodingType;
	private static Properties pro = System.getProperties();
	private static String strMailFrom;
	private static final Logger log = Logger.getLogger(EmailSender.class);
	static{
		try{
			String strHost = Repository.getRepository().getSystemProperty("mailServer");
			contentAndEncodingType = Repository.getRepository().getSystemProperty("contentAndEncodingType");
			strMailFrom = Repository.getRepository().getSystemProperty("mailFrom");
			pro.setProperty("mail.transport.protocol","smtp");
			pro.setProperty("mail.host",strHost);
			
			//specific to Gmail
			pro.put("mail.smtp.auth","true");  
			pro.put("mail.smtp.port","465");  
			pro.put("mail.debug","true");
			pro.put("mail.smtp.socketFactory.port","465");  
			pro.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
			pro.put("mail.smtp.socketFactory.fallback","false");
		}
		catch (Exception e) {
			log.error("Mail sender construction error", e);
			throw new RuntimeException(e);
		}
	}	
	
	public static void dispatchDynamicContentEmail(List<String> emailIds, String subject, Map<String, String> variableStrings, String templateName, long ownerId){
		try {
			Session mailSession = Session.getDefaultInstance(pro, new GJMailAuthenticator());
			mailSession.setDebug(true);
			MimeMessage msg = new MimeMessage(mailSession);
			msg.setSender(new InternetAddress(strMailFrom));
			InternetAddress[] address = new InternetAddress[emailIds.size()];
			int i=0;
			for(String emailId : emailIds){
				address[i] = new InternetAddress(emailId);
				i++;
			}
			String strMessage = MessageCreation.getMessage(variableStrings, templateName);
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setContent(strMessage, contentAndEncodingType);
			InternetAddress[] repaddress = { new InternetAddress(strMailFrom) };
			msg.setReplyTo(repaddress);
			msg.setSubject(subject);
			msg.setSentDate(new Date());
			new EmailProcessorThread(msg).start();
		} catch (Exception e) {
			log.error("Mail sending error", e);
		}
	}

	public static boolean dispatchStaticContentEmail(Communication communication){
		boolean result = false;
		try {
			Session mailSession = Session.getDefaultInstance(pro, new GJMailAuthenticator());
			mailSession.setDebug(true);
			MimeMessage msg = new MimeMessage(mailSession);
			msg.setSender(new InternetAddress(strMailFrom));
			InternetAddress[] address = {new InternetAddress(communication.getEmailId())};
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setContent(communication.getContent(), contentAndEncodingType);
			InternetAddress[] repaddress = { new InternetAddress(strMailFrom) };
			msg.setReplyTo(repaddress);
			msg.setSubject(communication.getEmailSubject());
			msg.setSentDate(new Date());
			Transport.send(msg);
			result = true;
		} 
		catch (Exception e) {
			log.error("Mail sending error", e);
		}
		return result;
	}
	
	private static class  EmailProcessorThread extends Thread{
        private MimeMessage msg;
        EmailProcessorThread(MimeMessage message){
        	msg = message;
        }
        public void run(){
            try {
            	Transport.send(msg);
            } catch (Exception e) {
                log.error("Mail sending error", e);
            }
        }
	}
}
